package com.hgxd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgxd.annotation.OperationLogAnnotation;
import com.hgxd.base.PageEntity;
import com.hgxd.entity.pojo.Slave;
import com.hgxd.entity.res.ResQOQAnalysis;
import com.hgxd.entity.res.TotalElectricalEnergy;
import com.hgxd.entity.vo.*;
import com.hgxd.entity.res.ResYOYAnalysis;
import com.hgxd.exception.ServiceException;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.ISlaveHistoryService;
import com.hgxd.service.ISlaveService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.hgxd.result.Result;

import com.hgxd.entity.pojo.SlaveHistory;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 从机变量记录表 前端控制器
 * </p>
 *
 * @author fsd
 * @since 2023-10-18
 */
@Api(tags = "从机变量记录表")
@RestController
@RequestMapping("/api/slaveHistory")
@CrossOrigin
public class SlaveHistoryController {
    @Resource(name = "SlaveHistoryServiceImpl")
    private ISlaveHistoryService slaveHistoryService;

    @Resource(name = "SlaveServiceImpl")
    private ISlaveService slaveService;

    /**
     * 得到总电量历史
     */
    @PostMapping("/getTotalElectricityHistory")
    @ApiOperation(value = "得到总电量历史", notes = "得到总电量历史")
    @OperationLogAnnotation(operModule = "从机变量记录管理-得到总电量历史", operType = "获取", operContent = "得到总电量历史")
    public Result<HashMap<LocalDate, Integer>> getTotalElectricityHistory() {
        return Result.ok(slaveHistoryService.getTotalElectricityHistory());
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增从机变量记录", notes = "传入从机变量记录对象，无需传入id")
    @OperationLogAnnotation(operModule = "从机变量记录管理-新增", operType = "新增", operContent = "新增从机变量")
    public Result<Boolean> insert(@RequestBody SlaveHistory slaveHistory) {
        return Result.ok(slaveHistoryService.save(slaveHistory));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改从机变量记录", notes = "需要传入id")
    @OperationLogAnnotation(operModule = "从机变量记录管理-修改", operType = "修改", operContent = "修改从机变量")
    public Result<Boolean> update(@RequestBody SlaveHistory slaveHistory) {
        return Result.ok(slaveHistoryService.updateById(slaveHistory));
    }

    /**
     * 根据id删除
     */
    @PostMapping("/delete/{id}")
    @ApiOperation(value = "根据id删除从机变量记录", notes = "需传入id")
    @OperationLogAnnotation(operModule = "从机变量记录管理-删除", operType = "删除", operContent = "根据id删除从机变量")
    public Result<Boolean> delete(@PathVariable Integer id) {
        return Result.ok(slaveHistoryService.removeById(id));
    }

    /**
     * 批量删除
     */
    @PostMapping("/del/batch")
    @ApiOperation(value = "批量删除从机变量记录表", notes = "传入ids")
    @OperationLogAnnotation(operModule = "从机变量记录管理-批量删除", operType = "删除", operContent = "批量删除从机变量")
    public Result<Boolean> deleteBatch(@RequestBody List<Integer> ids) {
        return Result.ok(slaveHistoryService.removeByIds(ids));
    }

    /**
     * 查询全部
     */
    @GetMapping("/getAll")
    @ApiOperation(value = "查询全部", notes = "无需传参")
    @OperationLogAnnotation(operModule = "从机变量记录管理-查询全部", operType = "查询", operContent = "查询所有从机变量")
    public Result<List<SlaveHistory>> findAll() {
        return Result.ok(slaveHistoryService.list());
    }

    /**
     * 根据id查询一个
     */
    @GetMapping("getById/{id}")
    @ApiOperation(value = "根据id查询", notes = "传入id")
    @OperationLogAnnotation(operModule = "从机变量记录管理-根据id查询", operType = "查询", operContent = "根据id查询从机变量")
    public Result<SlaveHistory> findOne(@PathVariable Integer id) {
        return Result.ok(slaveHistoryService.getById(id));
    }

    /**
     * 分页模糊查询
     */
    @GetMapping("/get/page")
    @ApiOperation(value = "分页模糊查询")
    @OperationLogAnnotation(operModule = "从机变量记录管理-分页模糊查询", operType = "查询", operContent = "分页查询从机变量")
    public Result<Page<SlaveHistory>> findPage(@RequestBody PageEntity pageEntity) {
        QueryWrapper<SlaveHistory> queryWrapper = new QueryWrapper<>();
        // 倒序查询
        queryWrapper.orderByDesc("id");
        return Result.ok(slaveHistoryService.page(new Page<>(pageEntity.getPageNum(), pageEntity.getPageSize()), queryWrapper));
    }

    /**
     * 报表查询 日报月报年报
     */
    @PostMapping("/searchDate")
    @ApiOperation(value = "报表查询，日报月报年报", notes = "记得添加type")
    @OperationLogAnnotation(operModule = "从机变量记录管理-报表查询，日报月报年报", operType = "查询", operContent = "报表查询，日报月报年报")
    public Result<List<SlaveHistoryMsgVo>> selectDay(@RequestBody SlaveHistoryVo slaveHistoryVo) {
        LambdaQueryWrapper<Slave> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Slave::getEquipmentId,slaveHistoryVo.getSlaveId());
        List<Integer> slaveIds = slaveService.list(queryWrapper).stream().map(Slave::getId).collect(Collectors.toList());
        slaveHistoryVo.setSlaveId(null);
        slaveHistoryVo.setSlaveIds(slaveIds);
        List<SlaveHistoryMsgVo> slaveHistoryInfo = slaveHistoryService.getSlaveHistoryInfo(slaveHistoryVo);
        return Result.ok(slaveHistoryInfo);
    }

    /**
     * 获取同比
     *
     * @return
     */
    @PostMapping("/getYOY")
    @ApiOperation(value = "获取同比", notes = "传入对应数据")
    @OperationLogAnnotation(operModule = "从机变量记录管理-获取同比", operType = "查询", operContent = "获取同比")
    public Result<List<ResYOYAnalysis>> getYOY(@RequestBody YOYVo yoyVo) {
        return Result.ok(slaveHistoryService.getYOY(yoyVo));
    }

    /**
     * 获取环比
     *
     * @return
     */
    @PostMapping("/getQOQ")
    @ApiOperation(value = "获取环比", notes = "传入对应数据")
    @OperationLogAnnotation(operModule = "从机变量记录管理-获取环比", operType = "查询", operContent = "获取环比")
    public Result<List<ResQOQAnalysis>> getQOQ(@RequestBody QOQVo qoqVo) {
        return Result.ok(slaveHistoryService.getQOQ(qoqVo));
    }

    @PostMapping("/getElectricalEnergy")
    @ApiOperation(value = "电能集抄", notes = "必须传入相对应的时间区间")
    @OperationLogAnnotation(operModule = "从机变量记录管理-电能集抄", operType = "查询", operContent = "电能集抄")
    public Result<List<TotalElectricalEnergy>> getElectricalEnergy(@RequestBody ResTotalElectricalEnergyVo totalElectricalEnergyVo) {
        return Result.ok(slaveHistoryService.getElectricalEnergy(totalElectricalEnergyVo));
    }

    @GetMapping("/getQOQDay")
    @ApiOperation(value = "获取所有从机当日环比及总电能")
    @OperationLogAnnotation(operModule = "从机变量记录管理-获取所有从机当日环比及总电能", operType = "查询", operContent = "获取所有从机当日环比及总电能")
    public Result<Map<String, String>> getQOQDay() {

        //获取所有从机名
        List<String> slaveNames = slaveService.list().stream()
                .map(Slave::getName).collect(Collectors.toList());
        //组装环比参数
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        QOQVo qoqVo = new QOQVo();
        qoqVo.setType(3);
        qoqVo.setTime(today);
        qoqVo.setSlaveNames(slaveNames);
        //计算每个环比
        List<ResQOQAnalysis> listToday = slaveHistoryService.getQOQ(qoqVo);
        //组装返回值
        //本期
        double nowEnergyConsumptionTotal = listToday.stream()
                .map(ResQOQAnalysis::getNowEnergyConsumption)
                .reduce(0.0, Double::sum);

        //上期
        qoqVo.setTime(today.minusDays(1));
        List<ResQOQAnalysis> listYesterday = slaveHistoryService.getQOQ(qoqVo);
        double lastEnergyConsumptionTotal = listYesterday.stream()
                .map(ResQOQAnalysis::getNowEnergyConsumption)
                .reduce(0.0, Double::sum);
        //防止上期为0，系统报错
        if (lastEnergyConsumptionTotal == 0) {
            throw new ServiceException(ResultCodeEnum.DATA_ERROR, "上期数据为0，无法计算");
        }
        //环比
        BigDecimal bigDecimal = BigDecimal.valueOf((nowEnergyConsumptionTotal - lastEnergyConsumptionTotal) / lastEnergyConsumptionTotal * 100);
        BigDecimal roundedNumber = bigDecimal.setScale(2, RoundingMode.HALF_UP);
        double qoq = roundedNumber.doubleValue();
        //组装返回值
//        ResQOQAnalysis resQOQAnalysis = new ResQOQAnalysis();
//        resQOQAnalysis.setSlaveName("全部从机");
//        resQOQAnalysis.setNowEnergyConsumption(nowEnergyConsumptionTotal);
//        resQOQAnalysis.setLastEnergyConsumption(lastEnergyConsumptionTotal);
//        resQOQAnalysis.setQOQ(qoq);
        HashMap<String, String> map = new HashMap<>();
        map.put("slaveName","全部从机");
        map.put("nowEnergyConsumption",String.format("%.2f",nowEnergyConsumptionTotal));
        map.put("lastEnergyConsumption",String.format("%.2f",lastEnergyConsumptionTotal));
        map.put("qoq",String.format("%.2f",qoq));
        return Result.ok(map);
    }

}

